from django.db import transaction
from rest_framework import permissions
from rest_framework.decorators import action

from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import SystemLog, Upload
from utils.exceptions import CustomError
from .serializers import WorkerSerializer
from .models import Worker
from .filters import WorkerFilter


# Create your views here.

class WorkerViewSet(CustomModelViewSet):
    # 后台Worker CRUD操作
    permission_classes = [permissions.IsAdminUser]
    queryset = Worker.objects.filter()
    serializer_class = WorkerSerializer

    def filter_queryset(self, queryset):
        print(self.request.GET)
        f = WorkerFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    # def create(self, request, *args, **kwargs):
    #     try:
    #         with transaction.atomic():
    #             serializer = self.get_serializer(data=request.data)
    #             # raise_exception 标志，如果存在验证错误，将会抛出 serializers.ValidationError 异常
    #             if serializer.is_valid(raise_exception=True):
    #                 file_id = request.data['file_id']
    #                 upload = Upload.objects.filter(id=file_id).first()
    #                 if not upload:
    #                     return response_error('封面图片文件不存在')
    #                 # 有时您会希望您的视图代码能够在保存实例时注入额外的数据。此额外数据可能包括当前用户,您可以通过在调用 .save() 时包含其他关键字参数来执行此操作
    #                 serializer.save(face_path=upload)
    #                 return response_ok()
    #     except Exception as e:
    #         import traceback
    #         traceback.print_exc()
    #         return response_error(str(e))

    def perform_create(self, serializer):
        super(WorkerViewSet, self).perform_create(serializer)
        instance = serializer.instance
        SystemLog.objects.add_log(self.request.user, SystemLog.INSERT, '新增工人(id=%s)信息' % instance.id)

    @action(methods=['post'], detail=True)
    def upload_face(self, request, pk):
        # 上传头像
        try:
            file = request.FILES.get('file')
            if not file:
                raise CustomError(u'未找到上传的数据')
            worker = Worker.get_instance_by_id(pk)
            with transaction.atomic():
                instance = Upload.objects.upload(file, 'worker')
                worker.face = instance
                worker.save()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()
